/*******************************************************************************

License: 
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain. 

This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements.  Therefore, it is 
permissible to distribute this software as a free download from the internet.

Disclaimer: 
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.

This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.

By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials.  You agree
to hold the Government harmless from any claim arising from your use
of the software.

*******************************************************************************/

/***********************************************************************
      LIBRARY: FING - NIST Fingerprint Systems Utilities

      FILE:           BZ_IO.C
      ALGORITHM:      Allan S. Bozorth (FBI)
      MODIFICATIONS:  Michael D. Garris (NIST)
                      Stan Janet (NIST)
      DATE:           09/21/2004
      UPDATED:        01/11/2012 by Kenneth Ko
      UPDATED:        03/08/2012 by Kenneth Ko
      UPDATED:        07/10/2014 by Kenneth Ko

      Contains routines responsible for supporting command line
      processing, file and data input to, and output from the
      Bozorth3 fingerprint matching algorithm.

***********************************************************************

      ROUTINES:
#cat: set_probe_filename - stores the name of the current probe file
#cat:            being processed
#cat: set_gallery_filename - stores the name of the current gallery file
#cat:            being processed
#cat: get_probe_filename - retrieves the name of the current probe file
#cat:            being processed
#cat: get_gallery_filename - retrieves the name of the current gallery
#cat:            file being processed
#cat: bz_load -  loads the contents of the specified XYT file into
#cat:            structured memory

***********************************************************************/


#include <string.h>
#include <ctype.h>
#include <sys/time.h>
#include "bozorth.h"


/***********************************************************************/

/* Used by the following set* and get* routines */
static char * pfile;
static char * gfile;

/***********************************************************************/
void set_probe_filename( char * filename ){
	pfile = filename;
}

/***********************************************************************/
void set_gallery_filename( char * filename ){
	gfile = filename;
}

/***********************************************************************/
char * get_probe_filename( void ){
	return pfile;
}

/***********************************************************************/
char * get_gallery_filename( void ){
	return gfile;
}

/************************************************************************
Load a 3-4 column (X,Y,T[,Q]) set of minutiae from the specified file
and return a XYT sturcture.
Row 3's value is an angle which is normalized to the interval (-180,180].
A maximum of MAX_BOZORTH_MINUTIAE minutiae can be returned -- fewer if
"max_minutiae" is smaller.  If the file contains more minutiae than are
to be returned, the highest-quality minutiae are returned.
*************************************************************************/

/***********************************************************************/
struct xyt_struct * bz_load( const char * xyt_file ){
	
	int nminutiae;
	int m;
	FILE * fp;
	struct xyt_struct * xyt_s;
	
	/* Temporary lists to store all the minutaie from a file */
	struct xytq_struct xytq_s;
	char xyt_line[ MAX_LINE_LENGTH ];
	
	fp = fopen( xyt_file, "r" );
	if ( !fp ){
		printf( "ERROR: fopen() of minutiae file \"%s\" failed: %s\n", xyt_file, strerror(errno) );
		return NULL;
	}
	
	nminutiae = 0;
	
	while( fgets(xyt_line, sizeof xyt_line, fp) ) {
		m = sscanf( xyt_line, "%d %d %d %d", &xytq_s.xcol[nminutiae], &xytq_s.ycol[nminutiae], &xytq_s.thetacol[nminutiae], &xytq_s.qualitycol[nminutiae] );
		if ( m == 3 ) xytq_s.qualitycol[nminutiae] = 1;
		else if( m != 4 ){
			printf( "ERROR: sscanf() failed on line %u in minutiae file \"%s\"\n", nminutiae+1, xyt_file );
			fclose(fp);
			return NULL;
		}
		++nminutiae;
		if ( nminutiae == MAX_FILE_MINUTIAE ) break;
	}
	
	fclose(fp);
	
	xytq_s.nrows = nminutiae;
	xyt_s = bz_prune( &xytq_s );
	
	return xyt_s;
} 

/************************************************************************
Load a XYTQ structure and return a XYT struct. 
Row 3's value is an angle which is normalized to the interval (-180,180].
A maximum of MAX_BOZORTH_MINUTIAE minutiae can be returned -- fewer if
"max_minutiae" is smaller.  If the file contains more minutiae than are
to be returned, the highest-quality minutiae are returned.
*************************************************************************/
struct xyt_struct * bz_prune( struct xytq_struct *xytq_s ){
	
	int nminutiae;
	//int index;
	int j;
	//int m;
	struct xyt_struct * xyt_s;
	int * xptr;
	int * yptr;
	int * tptr;
	int * qptr;
	struct minutiae_struct c[MAX_FILE_MINUTIAE];
	int xvals_lng[MAX_FILE_MINUTIAE],
		yvals_lng[MAX_FILE_MINUTIAE],
		tvals_lng[MAX_FILE_MINUTIAE],
		qvals_lng[MAX_FILE_MINUTIAE];
	int order[MAX_FILE_MINUTIAE];       
	int xvals[MAX_BOZORTH_MINUTIAE],
		yvals[MAX_BOZORTH_MINUTIAE],
		tvals[MAX_BOZORTH_MINUTIAE],
		qvals[MAX_BOZORTH_MINUTIAE];
	//char xyt_line[ MAX_LINE_LENGTH ];
	
	#define C1 0
	#define C2 1
	
	int i;
	nminutiae = xytq_s->nrows;  
	for ( i=0; i<nminutiae; i++ ) {
		xvals_lng[i] = xytq_s->xcol[i];
		yvals_lng[i] = xytq_s->ycol[i];
		
		if ( xytq_s->thetacol[i] > 180 ) tvals_lng[i] = xytq_s->thetacol[i] - 360;
		else                             tvals_lng[i] = xytq_s->thetacol[i];
		
		qvals_lng[i] = xytq_s->qualitycol[i];
	}
	
	if ( nminutiae > MAX_BOZORTH_MINUTIAE ) {
		printf( "WARNING: bz_prune(): trimming minutiae to the %d of highest quality\n", MAX_BOZORTH_MINUTIAE );
		
		if ( sort_order_decreasing( qvals_lng, nminutiae, order )) {
			printf( "ERROR: sort failed and returned on error\n" );
			return NULL;
		}
		
		for ( j = 0; j < nminutiae; j++ ) {
			
			if ( j == 0 ) continue;
			if ( qvals_lng[order[j]] > qvals_lng[order[j-1]] ) {
				printf( "ERROR: sort failed: j=%d; qvals_lng[%d] > qvals_lng[%d]\n", j, order[j], order[j-1] );
				return NULL;
			}
		}
		
		for ( j = 0; j < MAX_BOZORTH_MINUTIAE; j++ ) {
			xvals[j] = xvals_lng[order[j]];
			yvals[j] = yvals_lng[order[j]];
			tvals[j] = tvals_lng[order[j]];
			qvals[j] = qvals_lng[order[j]];
		}
		
		if ( C1 ) {
			qsort( (void *) &c, (size_t) nminutiae, sizeof(struct minutiae_struct), sort_quality_decreasing );
			for ( j = 0; j < nminutiae; j++ ) {
				if ( j > 0 && c[j].col[3] > c[j-1].col[3] ) {
					printf( "ERROR: sort failed: c[%d].col[3] > c[%d].col[3]\n", j, j-1 );
					return NULL;
				}
			}
		}
		
		xptr = xvals;
		yptr = yvals;
		tptr = tvals;
		qptr = qvals;
		
		nminutiae = MAX_BOZORTH_MINUTIAE;
	} else {
		xptr = xvals_lng;
		yptr = yvals_lng;
		tptr = tvals_lng;
		qptr = qvals_lng;
	}
	
	for ( j=0; j < nminutiae; j++ ) {
		c[j].col[0] = xptr[j];
		c[j].col[1] = yptr[j];
		c[j].col[2] = tptr[j];
		c[j].col[3] = qptr[j];
	}
	
	qsort( (void *) &c, (size_t) nminutiae, sizeof(struct minutiae_struct), sort_x_y );
	
	xyt_s = (struct xyt_struct *) malloc( sizeof( struct xyt_struct ) );
	if ( xyt_s == NULL ) {
		printf( "ERROR: malloc() failure of xyt_struct.");
		return NULL;
	}
	
	for ( j = 0; j < nminutiae; j++ ) {
		xyt_s->xcol[j]     = c[j].col[0];
		xyt_s->ycol[j]     = c[j].col[1];
		xyt_s->thetacol[j] = c[j].col[2];
	}
	xyt_s->nrows = nminutiae;
	
	return xyt_s;
}
